/******************************************************************************************
 * Import
 ******************************************************************************************/

// module
import Taro, { Component, getUserInfo } from '@tarojs/taro'
import { Swiper } from '@tarojs/components'
import { AtSwipeAction } from "taro-ui"

// project
import { CPage, CContent, CHeader, CFooter, CFloat, CAround, CBetween, CCenter, CRow, CWrap, CLine, CHand, CItemX, CItemY, CText, CLabel, CSvg, CImage, CButton , CColumn } from '../../library/comp';
import { Base64, Gen, Time, Zip, Session, Storage, Http, Toast, Modal } from '../../library/func';
import Icon from '../../project/style/icon';

import ConfigNet from '../../project/func/http/http'

/******************************************************************************************
 * Export Class
 ******************************************************************************************/

export default class Index extends Component {

	/*------------------------------------------------------------------------------------
	 * 初始化
	 *-----------------------------------------------------------------------------------*/
	constructor(props) {
		super(props);

		/**
		 * state
		 */
		this.state = {
			// 购物车数据
            cart: [],
            // 商品总价格
            amountAll: 0,
            // 全选
			allchecked: 1,
			
			// 删除组件显示
			isdel: 0
		}
	}

	/*------------------------------------------------------------------------------------
	 * 生命周期
	 *-----------------------------------------------------------------------------------*/
	// willMont
	componentWillMount() {
        this.setState({
			id: this.$router.params.id
		})
		console.log(111111111111111111)
		// 获取用户信息，判定身份
		ConfigNet.get({
			url: 'usercenter/info.php',
			
			success: (data)=> {
				this.setState({
					userInfo: data
				})
			},
			error: (res)=> {
				console.log('逻辑错误',res);
			},
		});
	}

	componentDidShow(){
		// 获取购物车数据
		ConfigNet.get({
			url: 'cart/list.php',
			success: (data)=> {

				console.log('购物车===================',data[0].product_object.set_image_small)

				var sum = 0

                if(data == ''){
                    this.setState({
                        allchecked: 0
                    })
                }
                
                for(var i of data){
                    if(i.is_checked == 0){
                        i.is_checked = false
                        this.setState({
                            allchecked: 0
                        })
                    }
                    if(i.is_checked == 1){
                        i.is_checked = true
                        sum += parseFloat((parseFloat(i.set_price)*parseInt(i.count)).toFixed(2))
                    }
                }
                this.setState({
                    cart: data,
                    amountAll: sum.toFixed(2),
                })
			},
			error: (res)=> {
				console.log('逻辑错误',res);
			},
		});

	}


	// didMount
	componentDidMount() {

		// 获取购物车数据
		ConfigNet.get({
			url: 'cart/list.php',
			success: (data)=> {

				var sum = 0

                if(data == ''){
                    this.setState({
                        allchecked: 0
                    })
                }
                
                for(var i of data){
                    if(i.is_checked == 0){
                        i.is_checked = false
                        this.setState({
                            allchecked: 0
                        })
                    }
                    if(i.is_checked == 1){
                        i.is_checked = true
                        sum += parseFloat((parseFloat(i.set_price)*parseInt(i.count)).toFixed(2))
                    }
                }
                this.setState({
                    cart: data,
                    amountAll: sum.toFixed(2),
                })
			},
			error: (res)=> {
				console.log('逻辑错误',res);
			},
		});
	}
	
	/*------------------------------------------------------------------------------------
	 * 事件处理
	 *-----------------------------------------------------------------------------------*/
	
    

	/*------------------------------------------------------------------------------------
	 * 自定义方法
	 *-----------------------------------------------------------------------------------*/
	config = {
        navigationBarTitleText: '购物车',
        navigationBarBackgroundColor: '#dd2f3c',
        navigationBarTextStyle: '#fff'
	}
	
	// 计算总额
    count_total(){
        var total_temp = 0;
        
        for(var product of this.state.cart){
            if(product.is_checked){
                total_temp += parseFloat((parseFloat(product.set_price)*parseInt(product.count)).toFixed(2))
            }
        }
        this.setState({
            amountAll: total_temp.toFixed(2)
        })
    }

    // 删除购物车单条数据
    _deleteOne(id,e){
        var that = this
        wx.showModal({
            title:'确定删除此商品吗?',
            showCancel: true,
            cancelText:'取消',
            cancelColor:'#000',
            confirmText:'确定',
            confrimColor:'#26a2ff',
            success:(res)=> {
                if(res.confirm){
                    ConfigNet.post({
                        url: 'cart/logic/delete.php',
                        data:{
                            id: id
                            // id: e.currentTarget.dataset.productid
                        },
                        success:(res)=> {

                            // 获取购物车数据
							ConfigNet.get({
								url: 'cart/list.php',
								success: (data)=> {

									var sum = 0

									if(data == ''){
										this.setState({
											allchecked: 0
										})
									}
									
									for(var i of data){
										if(i.is_checked == 0){
											i.is_checked = false
											this.setState({
												allchecked: 0
											})
										}
										if(i.is_checked == 1){
											i.is_checked = true
											sum += parseFloat((parseFloat(i.set_price)*parseInt(i.count)).toFixed(2))
										}
									}
									this.setState({
										cart: data,
										amountAll: sum.toFixed(2),
									})
								},
								error: (res)=> {
									console.log('逻辑错误',res);
								},
							});


                            wx.showToast({
                                title:'删除成功！',
                                icon:'success'
                            })


                        },
                        code(res) {
                            
                        },
                    })
                }
            }
        })
    }

    // 购物车 + 操作
    _add(id, index, event){
		ConfigNet.post({
			url: 'cart/logic/change.php',
			data: {
                id: id,
                type: 'add'
            },
			success: (data)=> {
				this.state.cart[index].count += 1
                this.count_total()
                this.setState({
                    
                })
			},
			error: (res)=> {
				Toast.text(res.msg)
				console.log('逻辑错误', res);
			},
		});
    }

    // subtract, 购物车 - 操作
    _subtarct(id, index, event) {
		ConfigNet.post({
			url: 'cart/logic/change.php',
			data: {
                id: id,
                type: 'subtract'
            },
			success: (data)=> {
				this.state.cart[index].count -= 1
                this.count_total()
                this.setState({
                    
                })
			},
			error: (res)=> {
				Toast.warn(res.msg)
			},
		});
    }

    // 选中/取消选中购物车单条数据
    _checkbox(index, id, e){

        if(this.state.cart[index].is_checked == 1) {
            this.state.cart[index].is_checked = 0
            this.state.allchecked = 0
            this.setState({

            })
        } else {
            this.state.cart[index].is_checked = 1

            // 判断当前是不是所有商品都处于选中状态，如是，则选中全选按钮
            for (var i in this.state.cart) {
                if(this.state.cart[i].is_checked == 1) {
                    this.state.allchecked = 1
                    this.setState({
                    
                    })
                } else {
                    this.state.allchecked = 0
                    this.setState({
                    
                    })
                    break
                }
            }

		}
		
		// 逻辑操作
		ConfigNet.post({
			url: 'cart/logic/check.php',
			data:{
                id: id,
                checked: this.state.cart[index].is_checked,
            },
			success: (data)=> {
				this.count_total()
			},
			error: (res)=> {
				console.log('逻辑错误',res);
			},
		});
    }

    // 全部选中/取消选中购物车所有数据
    _checkall(e){
        if (this.state.cart && this.state.cart.length == 0) {
			Toast.text('您的购物车还没有商品')
            return;
        }

        if(this.state.allchecked == 1) {
            this.state.allchecked = 0
            for (var i in this.state.cart) {
                this.state.cart[i].is_checked = 0
                this.setState({

                })
            }
        } else {
            this.state.allchecked = 1

            for (var i in this.state.cart) {
                this.state.cart[i].is_checked = 1
                this.setState({
                    
                })
            }
		}
		
		// 逻辑操作
		ConfigNet.post({
			url: 'cart/logic/checkAll.php',
			data:{
                checked: this.state.allchecked
            },
			success: (data)=> {
				this.count_total()
			},
			error: (res)=> {
				console.log('逻辑错误',res);
			},
		});
    }

    /**
     * 检查是否有选中条目，如果存在，则跳转到提交页，否则提示
     */
    navSubmit() {
        for (let item of this.state.cart) {
            if (item.is_checked) {
                wx.navigateTo({
                    url: '/screen/order/submit'
                });
                return;
            }
        }
        Toast.text('至少选中一种商品！');
	}
	
	/**
	 * 点击编辑显示删除组件
	 */
	edit() {
		if(this.state.isdel) {
			this.setState({
				isdel: 0
			})
		} else {
			this.setState({
				isdel: 1
			})
		}
	}

	/**
	 * 删除
	 */
	del() {
		Modal.confirm('确定删除该商品?', '', ()=>{
			// 组织数据，判断选中
			var ids = ''
			for (var i in this.state.cart) {
				if(this.state.cart[i].is_checked == 1) {
					ids += this.state.cart[i].id + ","
				}
			}

			//去掉最后一个逗号(如果不需要去掉，就不用写)
			if (ids.length > 0) {
				ids = ids.substr(0, ids.length - 1);
			}

			// 删除
			ConfigNet.post({
				url: 'cart/logic/batchDelete.php',
				data: {
					ids: ids,
				},
				success: (data)=> {
					Toast.success('删除成功！')
					
					// 获取购物车数据
					ConfigNet.get({
						url: 'cart/list.php',
						success: (data)=> {

							var sum = 0

							if(data == ''){
								this.setState({
									allchecked: 0
								})
							}
							
							for(var i of data){
								if(i.is_checked == 0){
									i.is_checked = false
									this.setState({
										allchecked: 0
									})
								}
								if(i.is_checked == 1){
									i.is_checked = true
									sum += parseFloat((parseFloat(i.set_price)*parseInt(i.count)).toFixed(2))
								}
							}
							this.setState({
								cart: data,
								amountAll: sum.toFixed(2),
							})
						},
						error: (res)=> {
							console.log('逻辑错误',res);
						},
					});

				},
				error: (res)=> {
					Toast.warn(res.msg)
				},
			});
		}, ()=>{

		})
	}
	/**
	 * 关闭其他条目
	 */
	closeSthing = index => {
		const list = this.state.cart.map((item, key) => {
			item.isClose = key !== index
			return item
		})
		this.setState({
			cart:list
		})
	}
	/**
	 * 提示 暂未开启此功能
	 */
	toToast () {
		Toast.text('暂未开启此功能')
	}

	/*------------------------------------------------------------------------------------
	 * 渲染
	 *-----------------------------------------------------------------------------------*/
	render () {
		console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&,,,,,,,,,,,,,,,,', this.state.cart[0].product_object.set_image_small)
		return (
			<CPage>
				<CContent>
					
					{/* 购物车数据 */}
					<CColumn ma='20' bg='#FFF' ra='20' pb='10'>
						<CBetween bb='2 solid #eee' px='20' h='80' lh='80' y='center'>
							<CItemX y='center'>
								<CSvg w='30' h='30' mr='20' color='#f60' icon={Icon.store} />
								<CText size='28' color='#555'>每日一达</CText>
							</CItemX>
							{this.state.isdel == 0 &&
							<CHand ba='2 solid #ddd' ra='10' di pa='5 12' size='24' color='#a6a6a6' onClick={this.edit}>编辑</CHand>
							}
							{this.state.isdel == 1 &&
							<CHand di pa='4 10' size='24' color='#333' onClick={this.edit}>完成</CHand>
							}
							
						</CBetween>
					
						<CheckboxGroup style='width:100%'>
							{this.state.cart.map((item, index) => {
								return (
									<AtSwipeAction 
										autoClose
										key={index}
										onClick={this._deleteOne.bind(this,item.id)}
										style='margin:10px auto;'
										isClose={item.isClose}
										options={item.options}
										onOpened={this.closeSthing.bind(this, index)}
										options={[
											{
												text:'删除',
												style:{
													backgroundColor:'#d53b31'
												}
											}
										]}
									 >
										<CBetween px='20' py='28'>
											<Checkbox class='f01' color='#c8322b' checked = {item.is_checked} onClick = {this._checkbox.bind(this, index, item.id)} data-checkboxid = {item.id} data-checked = {item.is_checked} style='transform: scale(1.6,1.6);padding-left:16rpx;'></Checkbox>
											<CItemX class='f09'>
												<Image lazyLoad={true} class='f03' style='width:150rpx; height:150rpx' src={'http://image.cdn.hesq.com.cn/rushbuy/product/'+item.product_object.set_image_small}/>
												<CColumn class='f07' x='left' pl='20' h='150'>
													<CHand color='#333' size='28' h='72' mb='28' oh lh='36'>{item.set_name}</CHand>
													<CBetween h='50' y='center'>
														<CHand color='#d53b31' size='30' bold >￥{item.set_price}</CHand>
														<CBetween class='f04'>
															<CSvg w='46' h='46' icon={Icon.sub} onClick={this._subtarct.bind(this, item.id, index)}></CSvg>
															<CHand size='36' color='#525252' mx='20'>{item.count}</CHand>
															<CSvg w='46' h='46' icon={Icon.add} onClick={this._add.bind(this, item.id, index)}></CSvg>
														</CBetween>
													</CBetween>
												</CColumn>
											</CItemX>

											{/* 左滑删除 */}
											{/* <CLabel>删除</CLabel> */}
										</CBetween>
									</AtSwipeAction>
								)
							})}
						</CheckboxGroup>
					</CColumn>

				</CContent>

				{/* Footer */}
				<CFooter h='100' bg='#fff' bt='1 solid #eee'>
					{isdel == 0 && 
					<CBetween>
						<CLine class='f07'>
							<CheckboxGroup style='padding-left:20rpx;display:flex;'>
								<CItemX y='center' x='center'>
									<Checkbox checked = {this.state.allchecked} onClick={this._checkall} data-checked = {this.state.allchecked}  style='transform: scale(1.6,1.6);padding-left:16rpx'></Checkbox>
									<CText size='30' color='#3b3b3b' mt='10' ml='10'>全选</CText>
								</CItemX>
							</CheckboxGroup>

							<CItemY x='right' y='center' class='f1' pr='20'>
								<CHand y='center'>
									<CText mr='10'>不含运费</CText>
									<CText size='28' mr='20'> 合计:</CText>
									<CHand size='28' color='#d53b31' bold>￥{this.state.amountAll}</CHand>
								</CHand>
								<CHand color='#ddd' size='26'>已享受 0 元优惠</CHand>
							</CItemY>
						</CLine>

						<CHand h='100' lh='100' x='center' color='#fff' bg='#d53b31' size='30' class='f03' onClick={this.navSubmit}>结算</CHand>
					</CBetween>
					}
					{isdel == 1 && 
					<CBetween y='center' h='100'>
						<CheckboxGroup class='f03' style='padding-left:20rpx'>
							<CItemX y='center'>
								<Checkbox checked = {this.state.allchecked} onClick={this._checkall} data-checked = {this.state.allchecked}></Checkbox>
								<CText size='28' color='#3b3b3b'>全选</CText>
							</CItemX>
						</CheckboxGroup>

						<CItemX x='right' y='center' class='f07' pr='20'>
							<CHand color='#333' ba='2 solid #ddd' size='28' x='center' pa='10 40' ra='40' mr='20' onClick={this.toToast}>移入关注</CHand>
							<CHand color='#333' ba='2 solid #ddd' size='28' x='center' pa='10 40' ra='40' onClick={this.del}>删除</CHand>
						</CItemX>
					</CBetween>
					}
				</CFooter>

			</CPage>
		)
	}
}


